﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Tools
{

   public class Tools
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            //设置参数
            //string jsonstr = JsonConvert.SerializeObject(postDataStr);
            byte[] payload = System.Text.Encoding.UTF8.GetBytes("data=" + postDataStr);
           // byte[] payload = System.Text.Encoding.UTF8.GetBytes(postDataStr);

            //请求数据内容长度*必须设置
            request.ContentLength = payload.Length;
            Stream sw = request.GetRequestStream();
            sw.Write(payload, 0, payload.Length);
            sw.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myStream = response.GetResponseStream();
            myStream.ReadTimeout = 6000;
            List<byte> BufferList = new List<byte>();
            byte[] ReceBuff = new byte[1024];

            int ReceLenth = myStream.Read(ReceBuff, 0, ReceBuff.Length);
            for (int j = 0; j < ReceLenth; j++)
            {
                BufferList.Add(ReceBuff[j]);
            }

            byte[] buffer = new byte[BufferList.Count];
            for (int j = 0; j < BufferList.Count; j++)
            {
                buffer[j] = BufferList[j];
            }
            response.Close();
            string retString = System.Text.Encoding.UTF8.GetString(buffer);

            return retString;
        }


        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
    }


}
